package ee.android.kinokavad.adapters;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import ee.android.kinokavad.R;
import ee.android.kinokavad.data.Movie;

public class MovieAdapter extends BaseExpandableListAdapter{

	private List<String> genres;
	private List<ArrayList<Movie>> movies;
	private LayoutInflater inflater;
	
	public MovieAdapter(Context context, List<String> genres, List<ArrayList<Movie>> moviesByGenre) {
		this.genres = genres;
		this.movies = moviesByGenre;
		this.inflater = LayoutInflater.from(context);
	}
	
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return movies.get(groupPosition).get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}
	
	private static class ChildViewHolder {
		private TextView movieName;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		ChildViewHolder holder = null;
		if (convertView == null) {
			holder = new ChildViewHolder();
			convertView = inflater.inflate(R.layout.movie_row, null);
			holder.movieName = (TextView) convertView.findViewById(R.id.movieRowTitle);
			convertView.setTag(holder);
		} else {
			holder = (ChildViewHolder) convertView.getTag();
		}
		
		Movie movie = movies.get(groupPosition).get(childPosition);
		
		holder.movieName.setText(movie.getTitle());
		
		return convertView;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return movies.get(groupPosition).size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return genres.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return genres.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	private static class GroupViewHolder {
		private TextView genre;
	}
	
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		
		GroupViewHolder holder = null;
		if (convertView == null) {
			holder = new GroupViewHolder();
			convertView = inflater.inflate(R.layout.genre_row, null);
			holder.genre = (TextView) convertView.findViewById(R.id.genreRowText);
			convertView.setTag(holder);
		} else {
			holder = (GroupViewHolder) convertView.getTag();
		}
		
		holder.genre.setText(genres.get(groupPosition));
		
		return convertView;
	}

	@Override
	public boolean hasStableIds() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}
	
}
